#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 设置根节点名称
    ui->treeWidget->setHeaderLabel("One Piece");

    // 设置顶层节点
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0, "海贼");
    // 添加到顶层节点
    ui->treeWidget->addTopLevelItem(item1);

    // 设置顶层节点
    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0, "革命军");
    // 添加到顶层节点
    ui->treeWidget->addTopLevelItem(item2);

    // 设置顶层节点
    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item3->setText(0, "海军");
    // 添加到顶层节点
    ui->treeWidget->addTopLevelItem(item3);

    // 添加子节点
    QTreeWidgetItem* item4 = new QTreeWidgetItem();
    item4->setText(0, "草帽海贼团");
    item1->addChild(item4);

    QTreeWidgetItem* item5 = new QTreeWidgetItem();
    item5->setText(0, "红发海贼团");
    item1->addChild(item5);

    QTreeWidgetItem* item6 = new QTreeWidgetItem();
    item6->setText(0, "黑胡子海贼团");
    item1->addChild(item6);

    QTreeWidgetItem* item7 = new QTreeWidgetItem();
    item7->setText(0, "龙");
    item2->addChild(item7);

    QTreeWidgetItem* item8 = new QTreeWidgetItem();
    item8->setText(0, "萨博");
    item2->addChild(item8);

    QTreeWidgetItem* item9 = new QTreeWidgetItem();
    item9->setText(0, "赤犬");
    item3->addChild(item9);

    QTreeWidgetItem* item10 = new QTreeWidgetItem();
    item10->setText(0, "黄猿");
    item3->addChild(item10);

    QTreeWidgetItem* item11 = new QTreeWidgetItem();
    item11->setText(0, "绿牛");
    item3->addChild(item11);

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_insertTopLevelItem_clicked()
{
    // 获取到输入框中的内容
    const QString text = ui->lineEdit->text();

    // 构造一个 QTreeWidgetItem
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);

    // 添加到顶层节点中
    ui->treeWidget->addTopLevelItem(item);

}

void Widget::on_pushButton_insertItem_clicked()
{
    // 获取到当前选中的节点
    QTreeWidgetItem* curItem = ui->treeWidget->currentItem();
    if (curItem == nullptr)
    {
        return ;
    }

    // 获取到输入框的内容
    const QString text = ui->lineEdit->text();

    // 构造一个 QTreeWidgetItem
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);

    // 插入到选中节点的子节点中
    curItem->addChild(item);

}


void Widget::on_pushButton_deleteItem_clicked(){
    // 获取到选中的元素
    QTreeWidgetItem* curItem = ui->treeWidget->currentItem();
    if (curItem == nullptr)
    {
        return ;
    }

    // 删除选中的元素, 需要先获取到父元素, 通过父元素进行删除
    QTreeWidgetItem* parent = curItem->parent();
    if (parent == nullptr)
    {
        // 顶层元素
        int index = ui->treeWidget->indexOfTopLevelItem(curItem);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        // 普通元素
        parent->removeChild(curItem);
    }


}
